package com.isoft.service.flight.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.dao.CommonMetaDao;
import com.isoft.dao.flight.FlightInfoDao;
import com.isoft.entity.CommonMeta;
import com.isoft.entity.flight.FlightInfo;
import com.isoft.service.flight.FlightInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author LiuGaoMing
 * @version 1.0
 * @description:航班时间信息服务层实现类
 * @date 2024/6/22 15:46
 */
@Service
public class FlightInfoServiceImpl extends ServiceImpl<FlightInfoDao, FlightInfo> implements FlightInfoService {
    @Autowired
    private FlightInfoDao flightInfoDao;
    @Autowired
    private CommonMetaDao commonMetaDao;
    @Autowired
    private CommonMeta commonMeta;

    @Override
    public List<FlightInfo> findAllFlightInfo() {
        return flightInfoDao.selectAllFlightInfo();
    }

    @Override
    public List<FlightInfo> findFlightInfoByCodeOrCftp(String CODE, String CFTP) {
        return flightInfoDao.selectFlightInfoByCodeOrCftp(CODE, CFTP);
    }

    @Override
    public List<FlightInfo> findFlightInfoByPage(Integer currentPage, Integer pageSize) {
        int offset = (currentPage - 1) * pageSize;
        return flightInfoDao.selectFlightInfoByPage(offset, pageSize);
    }

    @Override
    public Long selectFlightInfoCount() {
        return flightInfoDao.selectFlightInfoCount();
    }

    @Override
    public Boolean updateFlightInfo(FlightInfo flightInfo) {
       return flightInfoDao.updateFlightInfo(flightInfo)>0;
    }

    @Override
    public Boolean deleteFlightInfo(Integer ID) {
        FlightInfo info = flightInfoDao.selectFlightInfoByID(ID);
        int result = flightInfoDao.deleteFlightInfo(ID);
        if(result>0){
            commonMetaDao.deleteCommonMeta(info.getMETA_ID());
        }
        return result>0;
    }

    @Transactional // 确保这些操作在一个事务中执行
    public Boolean insertFlightInfo(FlightInfo flightInfo) {
//            当前表是BASE_CFIE表
        try {
//            因为是外键关联，所以先要插入meta表
            if (commonMetaDao.selectAllSEQN(flightInfo.getMETA_ID()) != null) {
                return false;
            }
            commonMeta.setSEQN(flightInfo.getMETA_ID());
            commonMeta.setCREATETIME(new Date());
            commonMeta.setSNDR("FIMS");
            commonMeta.setDDTM(new Date());
            commonMeta.setTYPE("BASE");
            commonMeta.setSTYP("CFIE");
            commonMetaDao.insertCommonMeta(commonMeta);
//            关闭插入自增
            flightInfoDao.enableIdentityInsert();
//            插入
            int result = flightInfoDao.insertFlightInfo(flightInfo);
            return result > 0;
        } finally {
            flightInfoDao.disableIdentityInsert();
        }
    }
}
